var pattern = new RegExp(/\?Code=(\S*)/g);
var idx = pattern.exec(window.location.href);

var grid05 = $('#jgTable05'),
    grid06 = $('#jgTable06'),
    grid5m = $('#jgTable5m'),
    grid6m = $('#jgTable6m');

var MDM003502 = [], MDM003503 = [], MDM003504 = [], MDM003505 = [], MDM003506 = [],
    gridSearch5m = [], gridSearch6m = [],
    checked05 = [], m5Data = [], checked06 = [], m6Data = [];
    
$(function(){
    requestAjax();
    gridInit05();
    gridInit06();
    gridInit5m();
    gridInit6m();
    $('li[data-opt="back"]').on('click', back);
    $('#BrandBtn').on('click', addBrand);
    $('#SKUBtn').on('click', addSKU);
    $('#addBrandBtn').on('click', addBrandBtn);
    $('#addSKUBtn').on('click', addSKUBtn);
    $("#opt_search_5").find(">i").on('click', function(){
        //console.log('jhhh')
        gridSearch5m.Content = {
            SearchText: $("#opt_search_5").find(">input").val()
        };
        grid5m.jqGrid("setGridParam",{postData: gridSearch5m}).trigger("reloadGrid");
    });
    $("#opt_search_6").find(">i").on('click', function(){
        gridSearch6m.Content = {
            SearchText: $("#opt_search_6").find(">input").val()
        };
        grid6m.jqGrid("setGridParam",{postData: gridSearch6m}).trigger("reloadGrid");
    });
    $('li[data-opt="u_save"],#js_submit').on('click', submitAll);
    $('.modal-data').draggable({cancel:'.u_modal_body, input'}); 
});

function requestAjax(){ //MDM003503
    if(idx){
        var _postData = Object.create(postData);    //请求头
        _postData.Method = 'Q';
        _postData.Content = {
            "Code": idx[1]
        }
        $.ajax({
            async: false,
            type: 'post',  
            url: mdmPath + '/MDM0035/MDM003503',
            data: _postData,
            dataType: 'json',
            success: function (re) {
                if (re.Status == 200) {
                    loadAjax(re);
                } else if (re.Status == -999) {
                    alert_QX($('body'), re.Message);
                } else {
                    myAlert(re.Message);
                }
            }         
        });        
    }    
}
function loadAjax(re){
    if(re.Status==200){    
        //console.log(re.Content)
        $('#ItemCode').val(re.Content.Code);
        $('#ItemName').val(re.Content.Name);
        MDM003502 = re.Content.MDM003502;
        MDM003503 = re.Content.MDM003503;
        MDM003504 = re.Content.MDM003504;
        MDM003505 = re.Content.MDM003505;
        MDM003506 = re.Content.MDM003506;
        //console.log(MDM003505.length)
        // if(MDM003505.length < 5){ 
        //     var num = 5 - MDM003505.length;
        //     for(var i=0;i<num;i++){
        //         MDM003505.push({});
        //     }
        // }
        // if(MDM003506.length < 8){ 
        //     var num = 8 - MDM003506.length;
        //     for(var i=0;i<num;i++){
        //         MDM003506.push({});
        //     }
        // }
    }else{
        myAlert(re.Message);
    }
}

function alarmFormatter(cellvalue, options, rowdata){
    var grid = $(this);
    if(JSON.stringify(rowdata)!=='{}'){
        cellvalue = '<a href="javascript:0" opt-data="'+grid[0].id+'_delete" title="删除"><i class="fa fa-trash-o"></i></a>';
    }else{
        cellvalue = '';
    }
    return cellvalue;
}

function gridInit05(){
    var gridData05 = Object.create(gridData);
    gridData05.grid = $('#jgTable05');
    gridData05.datatype = "local";
    gridData05.rowNum = 5;
    gridData05.colModel = [
        {label:'分类代码', name:'Code', sortable: false, hidden:true},
        {label:'行号', name:'LineID', sortable: false, hidden:true},
        {label:'序号', name:'OrderById', sortable: false, hidden:true},
        {label:'品牌代码', name:'BrandCode', sortable: false},
        {label:'品牌名称', name:'BrandName', sortable: false},
        //{label:'图片', name:'Picture_PC_Address', formatter: picFormatter, sortable: false},
        {label:'操作', name:'Options', width:80, align:'center', formatter: alarmFormatter, sortable: false}
    ];
    gridData05.beforeRequest = function(){
        gridData05.grid.jqGrid("setGridParam", {
            data : MDM003505,
        });
    };   
    gridData05.loadComplete = function(xhr){ 
        gridSize();
        $('a[opt-data="jgTable05_delete"]').unbind('click').bind('click',function(){
            var rowId = $(this).parent().parent()[0].id;
            var rowData = gridData05.grid.jqGrid("getRowData",rowId);
            gridData05.grid.jqGrid("delRowData",rowId);
            MDM003505.forEach(function(v,i,a){
                v.BrandCode == rowData.BrandCode
                &&a.splice(i,1);
            });
            // if(MDM003505.length < 5){ 
            //     var num = 5 - MDM003505.length;
            //     for(var i=0;i<num;i++){
            //         MDM003505.push({});
            //     }
            // }
        });
    };
    gridInit(gridData05);
}

function gridInit06(){
    var gridData06 = Object.create(gridData);
    gridData06.grid = $('#jgTable06');
    gridData06.datatype = "local";
    gridData06.rowNum = 8;
    gridData06.colModel = [
        {label:'分类代码', name:'Code', sortable: false, hidden:true},
        {label:'行号', name:'LineID', sortable: false, hidden:true},
        {label:'序号', name:'OrderById', sortable: false, hidden:true},
        {label:'SKU', name:'SKU', sortable: false},
        {label:'ItemName', name:'ItemName', sortable: false},
        //{label:'图片', name:'Picture_PC_Address', formatter: picFormatter, sortable: false},
        {label:'操作', name:'Options', width:80, align:'center', formatter: alarmFormatter, sortable: false}
    ];
    gridData06.beforeRequest = function(){
        gridData06.grid.jqGrid("setGridParam", {
            data : MDM003506,
        });
    };  
    gridData06.loadComplete = function(xhr){ 
        gridSize();
        $('a[opt-data="jgTable06_delete"]').unbind('click').bind('click',function(){
            var rowId = $(this).parent().parent()[0].id;
            var rowData = gridData06.grid.jqGrid("getRowData",rowId);
            gridData06.grid.jqGrid("delRowData",rowId);
            MDM003506.forEach(function(v,i,a){
                v.SKU == rowData.SKU
                &&a.splice(i,1);
            });
        });
    }
    gridInit(gridData06);
}

function gridInit5m(){

    var postData5m = {
        Method: 'Q',
        Content: {
            Category1: $('#ItemCode').val(),
            SearchText: ''
        }
    }
    for(i in postData){
        postData5m[i] = postData[i];
    };

    var gridData5m = Object.create(gridData);
    gridData5m.grid = $('#jgTable5m');
    gridData5m.pager = $('#jgPager5m');    
    //gridData5m.scroll = true;
    gridData5m.height = '390px';
    gridData5m.url = mdmPath + '/MDM0006/MDM000605';
    gridData5m.colModel = [
        {label:'代码', name:'Code'},
        {label:'名称', name:'Name'}
    ];
    // gridData5m.loadComplete = function(xhr){
        
    // };
    gridData5m.beforeRequest = function(){
        gridData5m.grid.jqGrid("setGridParam", {
            postData : postData5m,
        });
    };  
    gridData5m.sortname = 'Code';
    gridData5m.multiselect = true;
    gridInit(gridData5m);

    gridSearch5m = postData5m;

}

function gridInit6m(){

    var postData6m = {
        Method: 'Q',
        Content: {
            Putaway: 'Y',
            Category1: $('#ItemCode').val(),
            SearchText: ''
        }
    }
    for(i in postData){
        postData6m[i] = postData[i];
    };

    var gridData6m = Object.create(gridData);
    gridData6m.grid = $('#jgTable6m');
    gridData6m.pager = $('#jgPager6m');  
    gridData6m.height = '390px'; 
    gridData6m.url = mdmPath + '/MDM0004/MDM000402';
    gridData6m.colModel = [
        {label:'代码', name:'Code', width:80, sortable:false},
        {label:'名称', name:'Name'}
    ];
    gridData6m.beforeRequest = function(){
        gridData6m.grid.jqGrid("setGridParam", {
            postData : postData6m,
        });
    };  
    gridData6m.sortname = 'Code';
    gridData6m.multiselect = true;
    gridInit(gridData6m);

    gridSearch6m = postData6m;

}

//Options
function back(){
    window.open('MDM003501.html', '_self');
}
function addBrand(){
    $('#modal5').removeClass('hidden');
    gridSize();
}
function addSKU(){
    $('#modal6').removeClass('hidden');  
    gridSize();
}
function addBrandBtn(){
    // var n = 0;
    // MDM003505.forEach(function(v,i,a){
    //     JSON.stringify(v) == '{}' && n++;
    // });
    // for(var i=0;i<n;i++){
    //     MDM003505.pop();
    // }
    var rowIds = grid5m.jqGrid('getGridParam', 'selarrrow'); 
    var arr = [];
    rowIds.forEach(function(v,i,a){
        var temp = grid5m.jqGrid('getRowData', v);
        var status = true;
        MDM003505.forEach(function(v,i,a){
            v.BrandCode == temp.Code && (status = false);
        });
        status == true && arr.push({Code:$('#ItemCode').val(),BrandCode:temp.Code,BrandName:temp.Name})
    });
    MDM003505 = MDM003505.concat(arr);
    MDM003505.length > 5 && (MDM003505.length = 5);
    // if(MDM003505.length < 5){ 
    //     var num = 5 - MDM003505.length;
    //     for(var i=0;i<num;i++){
    //         MDM003505.push({});
    //     }
    // }
    grid05.trigger("reloadGrid");
    if(arr.length > 0){
        $('#modal5').addClass('hidden');
    }else{
        myAlert('请选择您要添加的品牌');
    }
}
function addSKUBtn(){
    var rowIds = grid6m.jqGrid('getGridParam', 'selarrrow'); 
    var arr = [];
    rowIds.forEach(function(v,i,a){
        var temp = grid6m.jqGrid('getRowData', v);
        var status = true;
        MDM003506.forEach(function(v,i,a){
            v.SKU == temp.Code && (status = false);
        });
        status == true && arr.push({Code:$('#ItemCode').val(),SKU:temp.Code,ItemName:temp.Name})
    });
    MDM003506 = MDM003506.concat(arr);
    MDM003506.length > 8 && (MDM003506.length = 8);
    grid06.trigger("reloadGrid");
    if(arr.length > 0){
        $('#modal6').addClass('hidden');
    }else{
        myAlert('请选择您要添加的SKU');
    }
}
function submitAll(){    //保存
    var Data05 = [], Data06 = [];
    MDM003505.forEach(function(v,i,a){
        Data05.push({Code:v.Code,LineID:i+1,OrderById:i+1,BrandCode:v.BrandCode,BrandName:v.BrandName});
    });
    MDM003506.forEach(function(v,i,a){
        Data06.push({Code:v.Code,LineID:i+1,OrderById:i+1,SKU:v.SKU,ItemName:v.ItemName});
    })
    var requestData = Object.create(postData);
    requestData.Method = 'U';
    requestData.Content = {
        Code: idx[1],
        Name: $('#ItemName').val(),
        MDM003502: MDM003502,
        MDM003503: MDM003503,
        MDM003504: MDM003504,
        MDM003505: Data05,
        MDM003506: Data06
    };
    console.log(requestData)
    $.ajax({
        type: "post",
        url: mdmPath+'/MDM0035/MDM003501',
        data: requestData,
        dataType: "json",
        success: function (re) {
            if (re.Status == 200) {
                myAlert('保存成功');
            } else {
                myAlert(re.Message);
            }
        }
    });
}

//样式
var gridWidth05 = $('.u_tabs_container');
var gridWidth06 = $('.u_tabs_container');
var gridWidth5m = $('.u_modal_body');
var gridWidth6m = $('.u_modal_body').eq(1);
function gridSize(){
    $('#jgTable05').setGridWidth(gridWidth05.width() - 30);
    $('#jgTable06').setGridWidth(gridWidth06.width() - 30);
    $('#jgTable5m').setGridWidth(gridWidth5m.width());
    $('#jgTable6m').setGridWidth(gridWidth6m.width());
}